const endpoint = 'cn-guangzhou.log.aliyuncs.com'
const project = ''
const logstore = ''
const userAgent = require('user-agent')

function getExtrData() {
  return {
    title: document.title,
    url: location.href,
    timestamp: Date.now(),
    userAgent: userAgent.parse(navigator.userAgent).name
  }
}

class SendTraker {
  constructor() {
    this.url = `http://${project}.${endpoint}/logstores/${logstore}/track`
    this.xhr = new XMLHttpRequest()
  }

  send(data) {
    const extraData = getExtrData()
    const log = { ...data, ...extraData }
    // 对象的值不能为数字
    for (const key in log) {
      if (typeof log[key] === 'number') {
        log[key] = `${log[key]}`
      }
    }

    const body = JSON.stringify({
      __logs__: [log]
    })

    this.xhr.open('POST', this.url, true)
    this.xhr.setRequestHeader('x-log-apiversion', '0.6.0')
    this.xhr.setRequestHeader('x-log-bodyrawsize', body.length)
    this.xhr.setRequestHeader('Content-Type', 'application/json')

    // this.xhr.onload = () => {
    //   console.log(this.xhr.response)
    // }
    // this.xhr.onerror = () => {
    //   console.log('send error')
    // }
    this.xhr.send(body)
  }
}
export default new SendTraker()
